package com.user.service.impl;

import com.user.domain.dto.PermissionDto;
import com.user.domain.pojo.Permission;
import com.user.mapper.PermissionMapper;
import com.user.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author 小杰大人
 * @since 2025-02-27
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Override
    public List<PermissionDto> getPermissionList() {
        List<Permission> list = this.list();
        Map<Long, PermissionDto> map = new TreeMap<>(); // 确保有序使用Tree
        list.stream().filter(
                permission -> {
                    if (permission.getParentId() == null){  // 一级权限
                        map.put(permission.getId(),PermissionDto.convert(permission));
                        return false;
                    }
                    return true;
                }
        ).forEach(
                permission -> {
                    PermissionDto convert = PermissionDto.convert(permission);
                    map.get(permission.getParentId()).getChildren().add(convert);
                }
        );
        return new ArrayList<>(map.values());
    }
}
